﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using XiaoGang.Soft.XGWMS.COM;
using Excel;
using System.IO;
using System.Reflection;

namespace XiaoGang.Soft.XGWMS.UI
{
    public partial class M014_BILLSCAN_Detail : FormBase
    {
        public M014_BILLSCAN_Detail(string strBillID)
        {
            this.strBillID = strBillID.Trim();
            InitializeComponent();
        }

        #region 变量定义

        BLL.BLL_M014BILLSCAN bll_M014BILLSCAN = new XiaoGang.Soft.XGWMS.BLL.BLL_M014BILLSCAN();
        string strBillID = "";
        private const string dataName = "流水";
       
        #endregion

        #region 窗口初始化

        protected void SetTableIndex()
        {
            int intIndex = 0;
            btnPrint.TabIndex = intIndex; intIndex++;
            btnClose.TabIndex = intIndex; intIndex++;
        }

        /// <summary>
        /// <p><b>方法名称</b>InitialGridView</p>
        /// <p><b>概要説明	:</b>Grid初始化</p>
        /// <p><b>作成者	:</b>万岗</p>
        /// <p><b>作成日	:</b>2008/09/10</p>
        /// </summary>
        protected void InitialGridView()
        {
            grdmentBillDetailInfo.Height = 379;
            grdmentBillDetailInfo.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Raised;
            grdmentBillDetailInfo.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            grdmentBillDetailInfo.ReadOnly = true;
            grdmentBillDetailInfo.ColumnHeadersHeight = 20;
            grdmentBillDetailInfo.ColumnHeadersVisible = true;
            grdmentBillDetailInfo.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;

            grdmentBillDetailInfo.Columns.Add("NO.", "NO.");
            grdmentBillDetailInfo.Columns.Add("GOODS_ID", "商品编码");
            grdmentBillDetailInfo.Columns.Add("GOODS_NM1", "商品名称1");
            grdmentBillDetailInfo.Columns.Add("UNITS", "数量");
            grdmentBillDetailInfo.Columns.Add("GOODS_GROUP_NM", "商品分类名称");
            grdmentBillDetailInfo.Columns.Add("BUYING_PRICE", "进价");
            grdmentBillDetailInfo.Columns.Add("SELLING_PRICE", "售价");
            grdmentBillDetailInfo.Columns.Add("STOREROOM_NM", "操作倉庫");
            grdmentBillDetailInfo.Columns.Add("PROVIDER", "供应商");
            grdmentBillDetailInfo.Columns.Add("PRODUCE_DATE", "生产日期");
            grdmentBillDetailInfo.Columns.Add("OVER_PRODUCE_DATE", "过期日期");
            grdmentBillDetailInfo.Columns.Add("MAX_WARN", "最大库存");
            grdmentBillDetailInfo.Columns.Add("MIN_WARN", "最小库存");
            grdmentBillDetailInfo.Columns.Add("BILLMEMO", "备注");

            grdmentBillDetailInfo.Columns["NO."].Width = 30;
            grdmentBillDetailInfo.Columns["NO."].Frozen = true;
            grdmentBillDetailInfo.Columns["NO."].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            grdmentBillDetailInfo.Columns["GOODS_ID"].Width = 80;
            grdmentBillDetailInfo.Columns["GOODS_NM1"].Width = 150;
            grdmentBillDetailInfo.Columns["GOODS_NM1"].Frozen = true;
            grdmentBillDetailInfo.Columns["GOODS_NM1"].Resizable = DataGridViewTriState.False;
            grdmentBillDetailInfo.Columns["GOODS_GROUP_NM"].Width = 126;
            grdmentBillDetailInfo.Columns["STOREROOM_NM"].Width = 96;
            grdmentBillDetailInfo.Columns["UNITS"].Width = 70;
            grdmentBillDetailInfo.Columns["UNITS"].CellTemplate.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdmentBillDetailInfo.Columns["BUYING_PRICE"].Width = 50;
            grdmentBillDetailInfo.Columns["BUYING_PRICE"].CellTemplate.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdmentBillDetailInfo.Columns["SELLING_PRICE"].Width = 50;
            grdmentBillDetailInfo.Columns["SELLING_PRICE"].CellTemplate.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdmentBillDetailInfo.Columns["PROVIDER"].Width = 100;
            grdmentBillDetailInfo.Columns["PRODUCE_DATE"].Width = 80;
            grdmentBillDetailInfo.Columns["OVER_PRODUCE_DATE"].Width = 80;
            grdmentBillDetailInfo.Columns["MAX_WARN"].Width = 80;
            grdmentBillDetailInfo.Columns["MAX_WARN"].CellTemplate.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdmentBillDetailInfo.Columns["MIN_WARN"].Width = 80;
            grdmentBillDetailInfo.Columns["MIN_WARN"].CellTemplate.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdmentBillDetailInfo.Columns["BILLMEMO"].Width = 126;
            grdmentBillDetailInfo.AllowUserToAddRows = false;
            grdmentBillDetailInfo.AllowUserToResizeColumns = true;
            grdmentBillDetailInfo.AllowUserToResizeRows = false;
            grdmentBillDetailInfo.RowHeadersVisible = false;
            grdmentBillDetailInfo.RowTemplate.Resizable = DataGridViewTriState.False;
            grdmentBillDetailInfo.RowTemplate.Height = 20;
            grdmentBillDetailInfo.RowTemplate.ReadOnly = true;
        }

        /// <summary>
        /// <p><b>方法名称</b>InitProcess</p>
        /// <p><b>概要説明	:</b>画面的初期化</p>
        /// <p><b>作成者	:</b>万岗</p>
        /// <p><b>作成日	:</b>2008/09/10</p>
        /// </summary>
        protected void InitProcess()
        {
            InitialGridView();
            SetTableIndex();
            ShowGrid(strBillID);
            grpBillDetailInfo.Text = "货单" + strBillID + "  共有" +  grdmentBillDetailInfo.Rows.Count + "件商品信息";
        }

        #endregion

        #region 方法

        /// <summary>
        /// <p><b>方法名称</b>ShowGrid</p>	
        /// <p><b>概要説明  :</b>Grid data display</p>	
        /// <p><b>作成者	:</b>万岗</p>	
        /// <p><b>作成日	:</b>2008/09/10</p>	
        /// <p><b>修改历史  :</b></p>	
        /// </summary>
        /// <param type="string" name="strBillID">货单编号</param>
        protected void ShowGrid(string strBillID)
        {
            ReturnValue rvGoods;
            rvGoods = bll_M014BILLSCAN.SearchGoodsDetail(strBillID);

            if (rvGoods.IsSuccess == false)
            {
                Method.MessageShow(rvGoods.ErrorID,dataName);
                return;
            }
            if (rvGoods.ResultDataSet.Tables[0].Rows.Count > 0)
            {
                if (rvGoods.ResultDataSet.Tables[0].Rows[0]["IN_OUT"].ToString().Trim() == "0")
                {
                    blTitle.Text = "入库";
                    lbInOutDate.Text = "入库时间：";
                }
                else
                {
                    blTitle.Text = "出库";
                    lbInOutDate.Text = "出库时间：";
                }
                lbUpdater.Text = rvGoods.ResultDataSet.Tables[0].Rows[0]["USER_NAME"].ToString().Trim();
                lbDoDate.Text = DateFormat(rvGoods.ResultDataSet.Tables[0].Rows[0]["BUSINESS_TIME"].ToString().Trim());
                lbMemo.Text = rvGoods.ResultDataSet.Tables[0].Rows[0]["M010MEMO"].ToString().Trim();
            }
            else
            {
                lbUpdater.Text = "";
                lbDoDate.Text = "";
                lbMemo.Text = "";
            }
            grdmentBillDetailInfo.Rows.Clear();
            foreach (DataRow row in rvGoods.ResultDataSet.Tables[0].Rows)
            {
                grdmentBillDetailInfo.Rows.Add(
                    (grdmentBillDetailInfo.Rows.Count + 1).ToString(),
                    row["GOODS_ID"].ToString().Trim(),
                    row["GOODS_NM1"].ToString().Trim(),
                    NumPriceFormat(row["UNITS"].ToString().Trim()),
                    row["GOODS_GROUP_NM"].ToString().Trim(),
                    row["BUYING_PRICE"].ToString().Trim()=="-1.0000"?"":string.Format("{0:f2}",decimal.Parse(row["BUYING_PRICE"].ToString().Trim())),
                    row["SELLING_PRICE"].ToString().Trim() == "-1.0000" ? "" : string.Format("{0:f2}",decimal.Parse(row["SELLING_PRICE"].ToString().Trim())),
                    row["STOREROOM_NM"].ToString().Trim(),
                    row["PROVIDER"].ToString().Trim(),
                    DateFormat((row["PRODUCE_DATE"].ToString().Trim())),
                    DateFormat(row["OVER_PRODUCE_DATE"].ToString().Trim()),
                    row["MAX_WARN"].ToString().Trim() == "-1" ? "" : row["MAX_WARN"].ToString().Trim(),
                    row["MIN_WARN"].ToString().Trim() == "-1" ? "" : row["MIN_WARN"].ToString().Trim(),
                    row["M009MEMO"].ToString().Trim());
            }
            if (grdmentBillDetailInfo.Rows.Count > 17)
            {
                grdmentBillDetailInfo.Columns["GOODS_NM1"].Width = 133;
            }
            else
            {
                grdmentBillDetailInfo.Columns["GOODS_NM1"].Width = 150;
            }
        }

        /// <summary>	
        /// <p><b>方法名称</b>DateFormat</p>	
        /// <p><b>概要説明  :</b>date data format</p>	
        /// <p><b>作成者	:</b>万岗</p>	
        /// <p><b>作成日	:</b>2008/09/10</p>	
        /// <p><b>修改历史  :</b></p>	
        /// </summary>
        /// <param name="strValue">没有格式化的字符串</param> 
        /// <returns type="string">格式化后的字符串</returns>
        protected string DateFormat(string strValue)
        {
            if (strValue.Length < 8)
            {
                return strValue;
            }
            return strValue.Substring(0, 4) + "/" +
                strValue.Substring(4, 2) + "/" +
                strValue.Substring(6, 2);

        }

        /// <summary>	
        /// <p><b>方法名称</b>NumPriceFormat</p>	
        /// <p><b>概要説明  :</b>num and price data format</p>	
        /// <p><b>作成者	:</b>万岗</p>	
        /// <p><b>作成日	:</b>2008/09/10</p>	
        /// <p><b>修改历史:</b></p>	
        /// </summary>
        /// <param name="strValue">没有格式化的字符串</param> 
        /// <returns type="string">格式化后的字符串</returns>
        protected string NumPriceFormat(string strValue)
        {
            string strTemp = strValue;
            if (strValue.Length > 6)
            {
                strTemp = strValue.Substring(0, strValue.Length - 6) + ","
                    + strValue.Substring((strValue.Substring(0, strValue.Length - 6)).Length, 3)
                    + "," + strValue.Substring(strValue.Length - 3, 3);

            }
            else if (strValue.Length > 3)
            {
                strTemp = strValue.Substring(0, strValue.Length - 3) + ","
                + strValue.Substring((strValue.Substring(0, strValue.Length - 3)).Length, 3);
            }
            return strTemp;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="myExcel"></param>
        /// <param name="dsData"></param>
        private void WriteExlWithDataTable(Excel.Application myExcel, DataSet dsData)
        {
            Excel.Workbook myBook = myExcel.Workbooks[1];
            Excel.Worksheet mySheet = (Excel.Worksheet)myBook.Worksheets[1];
            Excel.Range r;
            Excel.Range r1;
            for (int i = 0; i < dsData.Tables[0].Rows.Count; i++)
            {
                r = (Excel.Range)mySheet.Rows.get_Item(i + 6, Missing.Value);
                r.Copy(Missing.Value);
                r1 = (Excel.Range)mySheet.Rows.get_Item(i + 7, Missing.Value);
                r1.PasteSpecial(XlPasteType.xlPasteFormats, XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);
                myExcel.Cells[i + 6, 1] = "'" + (i + 1).ToString();
                myExcel.Cells[i + 6, 2] = "'" + dsData.Tables[0].Rows[i]["GOODS_ID"].ToString();
                //myExcel.Cells[i + 6, 3] = "'" + dsData.Tables[0].Rows[i]["GOODS_NO"].ToString();
                myExcel.Cells[i + 6, 3] = "'" + dsData.Tables[0].Rows[i]["GOODS_NM1"].ToString();
                myExcel.Cells[i + 6, 4] = "'" + dsData.Tables[0].Rows[i]["GOODS_NM2"].ToString();
                myExcel.Cells[i + 6, 5] = "'" + dsData.Tables[0].Rows[i]["GOODS_GROUP"].ToString();
                myExcel.Cells[i + 6, 6] = "'" + dsData.Tables[0].Rows[i]["PROVIDER"].ToString();
                myExcel.Cells[i + 6, 7] = "'" + dsData.Tables[0].Rows[i]["PRODUCE_DATE"].ToString();
                myExcel.Cells[i + 6, 8] = "'" + dsData.Tables[0].Rows[i]["OVER_PRODUCE_DATE"].ToString();
                //myExcel.Cells[i + 6, 10] = "'" + dsData.Tables[0].Rows[i]["OVER_DATE"].ToString();
                //myExcel.Cells[i + 6, 11] = "'" + dsData.Tables[0].Rows[i]["MAX_WARN"].ToString();
                //myExcel.Cells[i + 6, 12] = "'" + dsData.Tables[0].Rows[i]["MIN_WARN"].ToString();
                myExcel.Cells[i + 6, 9] = "'" + dsData.Tables[0].Rows[i]["BUYING_PRICE"].ToString();
                myExcel.Cells[i + 6, 10] = "'" + dsData.Tables[0].Rows[i]["SELLING_PRICE"].ToString();
                //myExcel.Cells[i + 6, 15] = "'" + dsData.Tables[0].Rows[i]["MEMO"].ToString();
            }
        }

        /// <summary>
        /// SaveFile
        /// </summary>
        /// <param name="strMobanName"></param>
        /// <param name="filename"></param>
        private void SaveFile(string strMobanName, out string filename)
        {
            SaveFileDialog mySave = new SaveFileDialog();
            mySave.Filter = "Excelﾎﾄｼ(*.XLS)|*.xls|ﾋﾐﾎﾄｼ(*.*)|*.*";
            if (mySave.ShowDialog() != DialogResult.OK)
            {
                filename = null;
                return;
            }
            else
            {
                filename = mySave.FileName;
                string filenameold = mySave.FileName;
                FileInfo mode = new FileInfo(System.Windows.Forms.Application.StartupPath.Trim() + "\\" + strMobanName);
                try
                {
                    mode.CopyTo(filename, true);
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message);
                    return;
                }
            }
        }

        #endregion

        #region 事件

        private void M014_BILLSCAN_Detail_Load(object sender, EventArgs e)
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            InitProcess();
        }

        /// <summary>
        /// btnClose_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            if (this.Cursor == Cursors.WaitCursor)
            {
                return;
            }
            this.Close();
        }

        /// <summary>
        /// btnPrint_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrint_Click(object sender, EventArgs e)
        {
            ReturnValue rvGoods;
            rvGoods = bll_M014BILLSCAN.SearchGoodsDetail(strBillID);
            if (rvGoods.IsSuccess == false)
            {
                Method.MessageShow(rvGoods.ErrorID,dataName);
                return;
            }
            GC.Collect();
            string filename = null;
            SaveFile("moban.xls", out filename);
            if (filename == null)
            {
                return;
            }
            //pictureBox1.Visible = true;
            object missing = Missing.Value;
            Excel.Application myExcel = new Excel.Application();
            myExcel.Application.Workbooks.Open(filename, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
            myExcel.Visible = false;
            WriteExlWithDataTable(myExcel, rvGoods.ResultDataSet);
            Excel.Workbook myBook = myExcel.Workbooks[1];
            Excel.Worksheet mySheet = (Excel.Worksheet)myBook.Worksheets[1];
            Excel.Range r = mySheet.get_Range(mySheet.Cells[6, 1], mySheet.Cells[rvGoods.ResultDataSet.Tables[0].Rows.Count + 5, rvGoods.ResultDataSet.Tables[0].Columns.Count + 5]);
            r.Select();
            myBook.Save();
            //pictureBox1.Visible = false;
            myExcel.Visible = true;
        }

        /// <summary>
        /// M014_BILLSCAN_Detail_KeyUp
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void M014_BILLSCAN_Detail_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F5:
                    btnPrint_Click(sender, e);
                    break;
                case Keys.Escape:
                    btnClose_Click(sender, e);
                    break;
            }
        }

        #endregion
    }
}